package com.todd.studentms.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import com.todd.studentms.entity.Person;
import com.todd.studentms.service.PersonService;
import com.todd.studentms.service.impl.PersonServiceImpl;
import com.todd.studentms.util.MyUtil;
import com.todd.studentms.util.SessionUtil;
import com.todd.studentms.util.Tdber;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@WebServlet("/person/*")
public class PersonServlet extends EssentialServlet {

    //  /get
    public List<Person> get(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res){
        Person person = JSONUtil.toBean(jsonObj,Person.class);
        System.out.println("AcceptEntity  >>> "+person);
        return new PersonServiceImpl().get(person);
    }

    // /getlike
    public List<Person> getlike(JSONObject jsonObj, HttpServletRequest req, HttpServletResponse res){
        Person person = JSONUtil.toBean(jsonObj,Person.class);
        System.out.println("AcceptEntity  >>> "+person);
        return new PersonServiceImpl().getLike(person);
    }

    // /add
    public boolean add(JSONObject jsonObj,HttpServletRequest req,HttpServletResponse res){
        Person person = JSONUtil.toBean(jsonObj,Person.class);
        System.out.println("AcceptEntity  >>> "+person);
        return new PersonServiceImpl().add(person.setId(MyUtil.randUUID()));
    }

    // /del
    public boolean doDelete(String[] ids,HttpServletRequest req,HttpServletResponse res){
        System.out.print("AcceptArray  >>> ");
        Arrays.stream(ids).forEach(id->System.out.print(id+" "));
        System.out.println();
        return new PersonServiceImpl().delete(Person.class,ids);
    }

    // /upd
    public boolean upd(JSONObject jsonObj,HttpServletRequest req,HttpServletResponse res){
        Person person = JSONUtil.toBean(jsonObj,Person.class);
        System.out.println("AcceptEntity  >>> "+person);
        return new PersonServiceImpl().update(person);
    }

    // /login
    public Person login(JSONObject jsonObject, HttpServletRequest req,HttpServletResponse res){
        Person person = JSONUtil.toBean(jsonObject,Person.class);
        System.out.println("AcceptEntity  >>> "+person);
        PersonServiceImpl personService = new PersonServiceImpl();
        Person loginingPerson = personService.getOne(person);
        if(loginingPerson==null&&loginingPerson.getId()==null){
            throw new RuntimeException("账号或密码错误");
        }
        // 登录成功
        return loginingPerson;
    }

}
